/**
 * @author scylla
 * @version V1.0
 * @Project echo-java-base
 * @Title 偶数检查
 * @Description *
 * @Package concurrent.mthread.bf
 * @Since 2021/8/12 4:38 下午
 */
package concurrent.mthread.bf;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EvenChecker implements Runnable {
    public static final int DEFAULT_COUNT = 10;
    private IntGenerator generator;
    private final int id;

    /**
     * 构造
     *
     * @param generator
     * @param id
     * @return {@link null}
     * @author chentl
     * @since 4:39 下午 2021/8/12
     **/
    public EvenChecker(IntGenerator generator, int id) {
        this.generator = generator;
        this.id = id;
    }

    @Override
    public void run() {
        for (int val; !generator.isCanceled(); ) {
            if ((val = generator.next()) % 2 != 0) {
                System.out.println("EventChecker{" + id + "}: " + val + " not even!");
                generator.cancel();//取消所有整数生成
            }
        }
    }


    /**
     * 指定生成器数量
     *
     * @param gp    生成器
     * @param count 数量
     * @return
     * @author chentl
     * @since 5:00 下午 2021/8/12
     **/
    public static void test(IntGenerator gp, int count) {
        System.out.println("Press Control-C to exit");

        ExecutorService exec = Executors.newCachedThreadPool();

        for (int i = 0; i < count; i++)
            exec.execute(new EvenChecker(gp, i));

        exec.shutdown();
    }

    /**
     * 指定生成器  默认10次
     *
     * @param gp
     * @author chentl
     * @since 5:00 下午 2021/8/12
     **/
    public static void test(IntGenerator gp) {
        test(gp, DEFAULT_COUNT);
    }
}
